package com.org.android.diary.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.org.android.diary.R;
import com.org.android.diary.adapter.ImageAdapter;
import com.org.android.diary.db.DiaryDao;
import com.org.android.diary.model.Diary;
import com.org.android.diary.service.RecordService;
import com.org.android.diary.utils.ImageUtils;
import com.org.android.diary.utils.LogUtil;
import com.org.android.diary.utils.PermissionUtil;
import com.org.android.diary.utils.TaoLinear;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 添加日志
 */
public class AddDiaryActivity extends Activity {
    private TextView timeTextView = null;
    private TextView weekTextView = null;
    private Spinner weatherSpinner = null;
    private Calendar cal = Calendar.getInstance();
    private Date date = null;
    private SimpleDateFormat simpleDateFormat = null;
    public static final int WEEKDAYS = 7;
    private EditText diaryInfo = null;
    private EditText diaryTitle = null;
    public static String[] WEEK = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
    private ImageView back = null;
    private SharedPreferences preferences = null;
    private RecyclerView recycler;
    private ImageView ivModuleAddImg;

    private ImageAdapter imageAdapter;
    private List<String> listImgs = new ArrayList<>();
    private List<String> listResults = new ArrayList<>();
    private String music = "music";

    private Button startBT;
    private Button stopBT;
    private Button playBT;
    private Intent service;
    private boolean isRecording;

    public static final int LOGINPRESSION = 0x11;
    public static final int REQUEST_CODE_LOCATION = 0x12;
    public static final int REQUEST_CODE_PRINCIPAL = 0x13;
    public static final int REQUEST_CODE_COPYREASION = 0x14;
    public static final int REQUEST_CODE_USER_SEARCH = 0x15;
    public static final int REQEEST_CDOE_GPS = 0x18;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }

    @Override
    protected void onResume() {
        super.onResume();
        setBackground();
    }

    @SuppressLint("SimpleDateFormat")
    private void init() {
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.add_diary);
        ivModuleAddImg = findViewById(R.id.ivModuleAddImg);
        ivModuleAddImg.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (PermissionUtil.cameraPermission(AddDiaryActivity.this, REQUEST_CODE_LOCATION)) {
                    Intent intent = new Intent("android.intent.action.PICK");
                    intent.setType("image/*");
                    startActivityForResult(intent, 3);
                } else {
                    Intent intent = new Intent("android.intent.action.PICK");
                    intent.setType("image/*");
                    startActivityForResult(intent, 3);
                }
            }
        });
        recycler = findViewById(R.id.recycler);

        imageAdapter = new ImageAdapter(this, listImgs);
        TaoLinear taoLinear = new TaoLinear(this, 3);
        taoLinear.setScrollEnabled(false);
        recycler.setLayoutManager(taoLinear);
        recycler.setItemAnimator(new DefaultItemAnimator());
        recycler.setAdapter(imageAdapter);

        preferences = getSharedPreferences("image", MODE_PRIVATE);
        date = cal.getTime();
        simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        timeTextView = (TextView) this.findViewById(R.id.time);
        timeTextView.setText(simpleDateFormat.format(date));
        weekTextView = (TextView) this.findViewById(R.id.week);
        weekTextView.setText(DateToWeek(date));
        weatherSpinner = (Spinner) this.findViewById(R.id.weather);
        diaryInfo = (EditText) this.findViewById(R.id.edit_diary_info);
        diaryTitle = (EditText) this.findViewById(R.id.edit_title);
        back = (ImageView) this.findViewById(R.id.back_add_diary);
        back.setOnClickListener(new BackListener());
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.weather, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
        weatherSpinner.setAdapter(adapter);
        weatherSpinner.setPrompt(getString(R.string.weather));
        setBackground();

        startBT = findViewById(R.id.button1);
        stopBT = findViewById(R.id.button2);
        playBT = findViewById(R.id.button3);
        service = new Intent(this, RecordService.class);
        isRecording = false;
    }

    private void setBackground() {
        LinearLayout layout = (LinearLayout) this.findViewById(R.id.add_diary_layout);
        int id = preferences.getInt("id", 0);
        if (id == 0) {
            layout.setBackgroundResource(R.drawable.diary_view_bg);
        } else if (id == 1) {
            layout.setBackgroundResource(R.drawable.diary_view_bg);
        } else if (id == 2) {
            layout.setBackgroundResource(R.drawable.spring);
        } else if (id == 3) {
            layout.setBackgroundResource(R.drawable.summer);
        } else if (id == 4) {
            layout.setBackgroundResource(R.drawable.autumn);
        } else if (id == 5) {
            layout.setBackgroundResource(R.drawable.winter);
        }
    }

    public static String DateToWeek(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int dayIndex = calendar.get(Calendar.DAY_OF_WEEK);
        if (dayIndex < 1 || dayIndex > WEEKDAYS) {
            return null;
        }
        return WEEK[dayIndex - 1];
    }

    class BackListener implements OnClickListener {

        @Override
        public void onClick(View v) {
            back();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            back();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @SuppressLint("WrongConstant")
    private void back() {
        if ((!diaryTitle.getText().toString().trim().equals("")) &&
                (!diaryInfo.getText().toString().trim().equals(""))) {
            DiaryDao diaryDao = new DiaryDao(AddDiaryActivity.this);
            Diary diary = new Diary();
            diary.setDate(timeTextView.getText().toString());
            diary.setWeek(weekTextView.getText().toString());
            diary.setWeather(weatherSpinner.getSelectedItem().toString());
            diary.setDiaryTitle(diaryTitle.getText().toString());
            diary.setDiaryInfo(diaryInfo.getText().toString());
            /**
             * 存储图片
             */
            if (listImgs.size() != 0) {
                Log.e("log", "图片字符串-->" + TextUtils.join(",", listImgs));
                diary.setImgs(TextUtils.join(",", listImgs));
            }
            diary.setMusic(music);
            diaryDao.insert(diary);
            Intent intent = new Intent();
            intent.setClass(AddDiaryActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
            overridePendingTransition(R.anim.push_below_in, R.anim.push_below_out);
            Toast.makeText(AddDiaryActivity.this, R.string.save_success, 0).show();
        } else {
            Toast.makeText(AddDiaryActivity.this, R.string.empty_info, 0).show();
            AddDiaryActivity.this.finish();
            overridePendingTransition(R.anim.push_below_in, R.anim.push_below_out);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_LOCATION:
                if (PermissionUtil.loginPermission(this, REQUEST_CODE_LOCATION)) {
                    Intent intent = new Intent("android.intent.action.PICK");
                    intent.setType("image/*");
                    startActivityForResult(intent, 3);
                }
                break;
            default:
        }
    }

    String capath;
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == 3) {
                if (data == null) {
                    return;
                }
                capath = ImageUtils.getInstance().getFilePathMethod(this, data.getData());
                LogUtil.e("接受地址-->" + capath);
                listImgs.add(capath);
                imageAdapter.notifyDataSetChanged();
            }
        }
    }

    public void start(View v){
        isRecording = true;
        setBtEnable(isRecording);
        startService(service);
    }
    public void stop(View v){
        isRecording = false;
        setBtEnable(isRecording);
        stopService(service);
    }

    private void setBtEnable(boolean flag) {
        startBT.setEnabled(!flag);
        stopBT.setEnabled(flag);
        playBT.setEnabled(!flag);
    }
    public void play(View v){
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.parse("/storage/emulated/0/test/20200423_133406.m4a"),"audio/*");
        startActivity(intent);
    }
    @SuppressLint("WrongConstant")
    public void delete(View v){

    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putBoolean("isRecording", isRecording);
        super.onSaveInstanceState(outState);
    }
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        isRecording = savedInstanceState.getBoolean("isRecording");
        setBtEnable(isRecording);
        super.onRestoreInstanceState(savedInstanceState);
    }
}
